package tom.reactor.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tom.reactor.model.User;
import tom.reactor.service.UserService;

import java.time.Duration;

/**
 * @author ZHUFEIFEI
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    @GetMapping("/{id}")
    public Mono<User> findOne(@PathVariable("id") Long id) {
        return this.service.findById(id);
    }

    @PostMapping
    public Mono<Void> addOne(@RequestBody User user) {
        return this.service.save(user).then();
    }

    @DeleteMapping("/{id}")
    public Mono<Void> removeOne(Long id) {
        return this.service.deleteById(id);
    }

    @GetMapping
    public Flux<User> findAll() {
        return this.service.findAll();
    }

    @GetMapping(value = "/per", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<User> findAllInterval() {
        //每秒钟返回一个，不是一次返回, 必须设置产生的数据类型为stream_json形式，不然是等了几秒但是还是一次返回的？？
        //和上面findAll区别是，上面是一次性全部返回数据为array,[user1,user2..],
        //此处延迟每个元素延迟一秒，得到的数据是user1一秒后user2... 是分开的一个一个的
        return this.service.findAll().delayElements(Duration.ofSeconds(1L));
    }


}
